package org.dey.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.LinkedHashMap;

/**
 * @author deyran
 * @date 2022/3/21 19:05
 * @classname
 * @see
 */
@Configuration
public class ShiroConfig {

    public ShiroConfig(){
        System.out.println("shiro启动");
    }

    /**
     * 核心配置1 配置shiro的SecurityManager
     */
    /*@Bean("securityManger")
    public SecurityManager newSecurityManger(AuthorizingRealm realm) { // shiro 包
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 通过realm访问数据库
        securityManager.setRealm(realm);
        return securityManager;
    }*/

    /**
     * 核心配置2 shiroFilterFactory工厂
     */
    /*@Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean newShiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        // 当此用户是一个非认证用户，需要先登录进行认证
        bean.setLoginUrl("/login.do");
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        // 必须授权/认证才能访问
        map.put("/**", "anon");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }*/

    /**
     * 下面3个方法用于生命周期管理,注意,如若需要在Controller中使用权限控制,需要将以下3个方法丢到AppServletConfig中,否则只会在Service中生效
     * @return
     */
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor newLifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 配置负责为Bean对象(需要授权访问的方法所在的对象)
     * 创建代理对象的Bean组件
     */
    @DependsOn(value = "lifecycleBeanPostProcessor")
    @Bean
    public DefaultAdvisorAutoProxyCreator newDefaultWebSecurityManager(){
        return new DefaultAdvisorAutoProxyCreator();
    }

    /**
     * 配置授权属性应用对象(在执行授权操作时需要用到此对象)
     * @param securityManager
     * @return
     */
    public AuthorizationAttributeSourceAdvisor newAuthorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor bean = new AuthorizationAttributeSourceAdvisor();
        bean.setSecurityManager(securityManager);
        return bean;
    }

}
